/**
 * This software is licensed under the MIT license. 
 */
package de.kune.sessionxs.matcher;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.kune.sessionxs.matcher.context.SessionMatcherContext;
import de.kune.sessionxs.matcher.context.StringValueContext;

/**
 * Provides client IP address-based matching. This matcher makes sure that all
 * requests of a session originate from the same IP address.
 * 
 * @author Alexander Kune
 * 
 */
public class ClientIPAddressMatcher extends AbstractSessionMatcher implements
		SessionMatcher {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(ClientIPAddressMatcher.class);

	@Override
	public SessionMatcherContext init(HttpServletRequest request) {
		return new StringValueContext(request.getRemoteAddr());
	}

	@Override
	public boolean matches(SessionMatcherContext context,
			HttpServletRequest request) {
		if (context instanceof StringValueContext) {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Context value: ["
						+ ((StringValueContext) context).getValue()
						+ "], request value: [" + request.getRemoteAddr() + "]");
			}
			return equalIpAddresses(((StringValueContext) context).getValue(),
					request.getRemoteAddr());
		} else {
			throw new IllegalArgumentException("Context must be of class ["
					+ StringValueContext.class.getName() + "].");
		}
	}

	private boolean equalIpAddresses(String address1, String address2) {
		if (address1 == address2) {
			return true;
		}
		if (address1 != null) {
			if (address1.equals(address2)) {
				return true;
			}
			if (address2 != null
					&& (address1.equals("0:0:0:0:0:0:0:1")
							&& address2.equals("127.0.0.1") || address2
							.equals("0:0:0:0:0:0:0:1")
							&& address1.equals("127.0.0.1"))) {
				return true;
			}
		}
		return false;
	}

}
